package com.edgelight.service.impl;

import com.edgelight.dao.NewsRepository;
import com.edgelight.pojo.News;
import com.edgelight.dao.NewsMapper;
import com.edgelight.pojo.resp.BaseResp;
import com.edgelight.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;


@Service
public class NewsServiceImpl implements NewsService {
    @Resource
    private NewsMapper newsDao;

    @Autowired
    NewsRepository newsRepository;

    /**
     * 通过ID查询单条数据

     */
    @Override
    public News queryById(Integer id) {
        return this.newsDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param news 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public Page<News> queryByPage(News news, PageRequest pageRequest) {
        long total = this.newsDao.count(news);
        return new PageImpl<>(this.newsDao.queryAllByLimit(news, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param news 实例对象
     * @return 实例对象
     */
    @Override
    public News insert(News news) {
        this.newsDao.insert(news);
        return news;
    }

    /**
     * 修改数据
     *
     * @param news 实例对象
     * @return 实例对象
     */
    @Override
    public News update(News news) {
        this.newsDao.update(news);
        return this.queryById(news.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.newsDao.deleteById(id) > 0;
    }

    @Override
    public BaseResp findAll(Integer page, Integer size) {
        PageRequest of = PageRequest.of(page, size);

        Page<News> all = newsRepository.findAll(of);
        return new BaseResp(0,"ok",all.getContent(),all.getTotalElements());

    }
    @Override
    public BaseResp insertOrUpdate(News news) {

        try {
            newsRepository.saveAndFlush(news);
        }catch (Exception e){
            return new BaseResp().ERROR();
        }


        return new BaseResp().SUCCESS();
    }

    @Override
    public BaseResp delete(Integer id) {
        BaseResp baseResp = new BaseResp();

        try {
            newsRepository.deleteById(id);
        }catch (Exception e){
            return baseResp.ERROR();
        }



        return baseResp.SUCCESS();
    }
}

